"""
PyQt5版GUI工具
"""
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from ui.Ui_main_window import Ui_MainWindow
import sys


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        # 创建对象
        self.ui = Ui_MainWindow()
        # 初始化内容
        self.ui.setupUi(self)
        self.pwm_value = 0
        self.speed = self.calc_motor_speed()

        # 初始化ui
        self.init_ui()
        self.init_data()

        # 初始化定时任务
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.on_timer)
        self.timer.start(10)

    def calc_motor_speed(self):
        # 0~100 -> -100~100
        # 根据pwm值计算电机速度
        return self.pwm_value * 2.0 - 100

    def on_timer(self):
        current_value = self.ui.dial_wheel.value()
        new_value = current_value + self.speed

        self.ui.dial_wheel.setValue(new_value)
        print("timer: ", new_value)

    def on_slider_back_valueChanged(self, value):
        print("back: ", value)
        self.pwm_value = value
        self.update_ui()

    def on_slider_front_valueChanged(self, value):
        print("front: ", value)
        self.pwm_value = 100 - value
        self.update_ui()

    def init_ui(self):
        pass

    def init_data(self):
        self.update_ui()

    def update_ui(self):
        self.ui.slider_front.setValue(100 - self.pwm_value)
        self.ui.slider_back.setValue(self.pwm_value)
        self.speed = self.calc_motor_speed()
        self.ui.lcd_speed.display(self.speed)
        self.ui.label_direction.setText("前进" if self.speed > 0 else "后退")

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
